package com.bw.lib_widget.test

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.bw.lib_widget.R
import me.jessyan.autosize.utils.AutoSizeUtils

/**
 * @author ytx
 * @date 2025-09-22 13:38
 * @description 绘制圆
 */
class MyView:View{
    //画笔
    private val paint = Paint()
    private var radius = 0f
    private var color = Color.BLUE

    //xml布局执行构造
    constructor(context: Context):this(context, null)
    //java代码执行
    constructor(context: Context, attrs: AttributeSet?):this(context,attrs,0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int):super(context,attrs,defStyleAttr){
        //获得自定义属性
        val typedArray = context?.obtainStyledAttributes(attrs, R.styleable.MyView)
        val myRadius = typedArray?.getFloat(R.styleable.MyView_myradius,100f)!!
        radius = AutoSizeUtils.dp2px(context, myRadius).toFloat() //将dp转换成px
        color = typedArray.getColor(R.styleable.MyView_mycolor,Color.BLUE)
        //回收：防止内存泄露
        typedArray.recycle()
        initPaint()
    }
    private fun initPaint() {
        paint.color = color//画笔颜色
        paint.style = Paint.Style.FILL //画笔样式 FILL：实心 STROKE：空心
        paint.strokeWidth = 5f //画笔粗细
        paint.isAntiAlias = true //抗锯齿
        paint.isDither = true //防抖
    }

    /**
     * canvas：画布
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //当前正中心绘制圆
        canvas.drawCircle(measuredWidth/2f,measuredHeight/2f,radius.toFloat(),paint)
    }

    /**
     * 测量自己大小？不测量wrap和match效果一样
     * 1)通过测量规格获得测量模式和大小
     * 2)判断测量模式为AT_MOST，自己计算宽度和高度
     * 3)调用setMeasureDimission设置宽度和高度
     *
     * widthMeasureSpec：宽度测量规格
     * heightMeasureSpec：高度测量规格
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //1)通过测量规格获得测量模式和大小
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        //2)判断测量模式为AT_MOST，自己计算宽度和高度
        if(widthMode == MeasureSpec.AT_MOST){
            widthSize = (radius * 2).toInt()
        }
        if (heightMode == MeasureSpec.AT_MOST){
            heightSize = (radius * 2).toInt()
        }
        //3)调用setMeasureDimission设置宽度和高度
        setMeasuredDimension(widthSize,heightSize)
    }


}